package array;

//长度最小的子数组
public class leetcode209 {
    public static void main(String[] args) {
        int[] nums = {2,3,1,2,4,3};
        int target = 7;
        int result = minSubArrayLen(target, nums);
        System.out.print(result);
    }

    public static int minSubArrayLen(int target, int[] nums){

        int result = nums.length + 1;
        int sum = 0;
        int start = 0;
        for(int end = 0; end < nums.length; end++){
            sum += nums[end];
            while(sum >= target){
                sum -= nums[start];
                if(end - start + 1 < result){
                    result = end - start + 1;
                }
                start++;
            }
        }
        if(result > nums.length) result = 0;
        return result;
    }

    public int minSubArrayLen2(int s, int[] nums) {
        int left = 0;
        int sum = 0;
        int result = Integer.MAX_VALUE;
        for (int right = 0; right < nums.length; right++) {
            sum += nums[right];
            while (sum >= s) {
                result = Math.min(result, right - left + 1);
                sum -= nums[left++];
            }
        }
        return result == Integer.MAX_VALUE ? 0 : result;
    }
}
